package cn.pomit.springbootwork.oauthclient2.web;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springbootwork.oauthclient2.model.IpModel;
import cn.pomit.springbootwork.oauthclient2.model.ResultModel;
import cn.pomit.springbootwork.oauthclient2.util.IPUtil;

@RestController
@RequestMapping("/api")
public class OauthClientRest {
	@Value("${security.oauth2.resource.userInfoUri}")
	private String userInfoUri;
	@Autowired
	private OAuth2RestTemplate oAuth2RestTemplate;

	@RequestMapping(value = "/ip", method = { RequestMethod.GET })
	public ResultModel ip(HttpServletRequest request) {
		IpModel ipModel = new IpModel();
		ipModel.setClientIpAddress(IPUtil.getIpAddr(request));
		ipModel.setServerIpAddress(IPUtil.localIp());
		return ResultModel.ok(ipModel);
	}

	@RequestMapping(value = "/test")
	public ResultModel test(Principal principal) {

		return ResultModel.ok(principal.getName());
	}

	@RequestMapping(value = "/userInfo")
	public ResultModel userinfo(Principal principal) {
		return oAuth2RestTemplate.getForObject(userInfoUri, ResultModel.class);
	}
}
